package com.gblfy.axis2.client;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.springframework.stereotype.Component;

import javax.xml.namespace.QName;

/**
 * axis2调用客户端
 *
 * @author gblfy
 * @date 2021-09-25
 */
@Component
public class Axis2WsClient {

    //默认超时时间20s
    public static final Long timeOutInMilliSeconds = 2 * 20000L;

    /**
     * axis2调用客户端
     *
     * @param url                   请求服务地址
     * @param nameSpace             命名空间
     * @param method                方法名
     * @param reqXml                请求报文
     * @param timeOutInMilliSeconds 超时时间
     * @return String 类型的响应报恩
     * @throws AxisFault 遇到异常则抛出不处理
     */
    public static String sendWsMessage(String url, String nameSpace, String method, String reqXml, long timeOutInMilliSeconds) throws AxisFault {
        String resXml = null;
        try {
            EndpointReference targetEPR = new EndpointReference(url);

            RPCServiceClient sender = new RPCServiceClient();
            Options options = sender.getOptions();
            options.setTimeOutInMilliSeconds(timeOutInMilliSeconds); //超时时间20s
            options.setTo(targetEPR);
            QName qName = new QName(nameSpace, method);
            Object[] param = new Object[]{reqXml};
            //这是针对返值类型的
            Class<?>[] types = new Class[]{String.class};
            Object[] response = sender.invokeBlocking(qName, param, types);
            resXml = response[0].toString();
            // System.out.println("响应报文:" + resXml);
        } catch (AxisFault e) {
            e.printStackTrace();
            throw e;
        }

        return resXml;
    }

    public static void main(String[] args) {
        try {
            String url = "http://localhost:8080/services/axis2Service?wsdl";
            String nameSpace = "http://service.axis2.gblfy.com";
            String method = "sayHello";
            String reqXml = "请求报文";
            String resXml = sendWsMessage(url, nameSpace, method, reqXml, timeOutInMilliSeconds);
            System.out.println("响应报文:" + resXml);
        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        }
    }
}